package edu.turtlekit2.warbot;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

import org.python.modules._codecs;

public class SingletonInfoAgent{

	private static SingletonInfoAgent 				_myInstance = null;
	private HashMap<String, Integer>				_hashCostAgent = null;
    private List<String>                        	_listClassAgent = null;
    private String									_path = "";
    private String									_pathBIN = "";
    private String									_package = "edu.turtlekit2.warbot.agents.";
	
	public static SingletonInfoAgent getInstance(){
		if(_myInstance == null){
			_myInstance = new SingletonInfoAgent();
		}
		
		return _myInstance;
	}
	
	public int getCost(String agentName){
		int retour = 0;
		if(_hashCostAgent == null){
			initHashMapCost();
		}

		try{
			retour = _hashCostAgent.get(agentName);
		}catch(Exception e){
			retour = Integer.MAX_VALUE;
		}
		return retour;
	}
	
	public Class getClass(String agentName) throws Exception{
		
		if(_hashCostAgent == null){
			initHashMapCost();
		}
		
		Class retour = null;
		
		File file = new File(_pathBIN);
        
        URL url = file.toURL();
        URL[] urls = new URL[]{url};

        // Create a new class loader with the directory
        ClassLoader c = new URLClassLoader(urls);
        
        retour = c.loadClass(_package+agentName);
		
		return retour;
	}
	
	public String findPathJar(Class<?> context) throws IOException {
		File f = null;
		try {
			f = new File(context.getProtectionDomain().getCodeSource().getLocation().toURI());
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        File z = new File(".");
        _pathBIN = f.getCanonicalPath() + "\\";
		return (f.getCanonicalPath() + "\\edu\\turtlekit2\\warbot\\agents\\").replace('\\', '/');
	}
	
	private void getClasseNamesInPackage (String packageName){
		if(_path.equals("")){
			try {
				_path = findPathJar(getClass());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
        List arrayList = new ArrayList ();
        _listClassAgent = new ArrayList<String>();
        
        File rep = new File(_path);
        File[] f = rep.listFiles();
        
        for(int i = 0 ; i < f.length ; ++i){
        	try {
				_listClassAgent.add((f[i].getCanonicalPath()).substring(0, (f[i].getCanonicalPath()).lastIndexOf(".")));
			} catch (IOException e) {
				System.out.println("rate");
			}
        }
    }
	
	private void initHashMapCost(){
		if(_listClassAgent == null){
			getClasseNamesInPackage("edu/turtlekit2/warbot");
		}
		_hashCostAgent = new HashMap<String, Integer>();
        Integer cost = 0;
        String tmp = "";

        for (int i= 0; i < _listClassAgent.size(); i++) {
            try {
                int j = _listClassAgent.get(i).lastIndexOf("\\");

                tmp = _listClassAgent.get(i).substring(j + 1, _listClassAgent.get(i).length());

                File file = new File(_pathBIN);
                
                URL url = file.toURL();          // file:/c:/myclasses/
                URL[] urls = new URL[]{url};

                // Create a new class loader with the directory
                ClassLoader c = new URLClassLoader(urls);
                
                Class c1 = c.loadClass(_package+tmp);
                Method m = c1.getMethod("getCost", null);
                Object temp = m.invoke(null, null);
                cost = (Integer) temp;
            } catch (Exception ex) {
                cost = 200;
            }
            _hashCostAgent.put(tmp, cost);
        }
        
    }
}